package com.doodle.common.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Observable;


public class SDCardHelper extends BroadcastReceiver {
	
	private static SDCardHelper sInstance = null;
	private Context mContext;
	private boolean mIsMounted = true;
	private final SDCardStateObservable mStateObservable = new SDCardStateObservable();
	
	public interface SDCardStateObserver {
		public void onChanged(boolean mounted);
	}
	
	public static void createInstance(Context context) {
		if (sInstance == null) {
			sInstance = new SDCardHelper(context);
		}
	}
	
	public static SDCardHelper getInstance() {
		return sInstance;
	}
	
	private SDCardHelper(Context context) {
		mContext = context;
		
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
		filter.addAction(Intent.ACTION_MEDIA_EJECT);
		filter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
		filter.addDataScheme("file");
		mContext.registerReceiver(this, filter);
		
		mIsMounted = Utils.isSDCardMounted();
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		if (Intent.ACTION_MEDIA_SCANNER_STARTED.equals(action)) {
			mIsMounted = true;
			notifyStateChanged(true);
		} else if (Intent.ACTION_MEDIA_EJECT.equals(action)) {
			mIsMounted = false;
			notifyStateChanged(false);
		}
	}
	
	public boolean isMounted() {
		return mIsMounted;
	}
	
	public void registerStateObserver(SDCardStateObserver observer) {
		mStateObservable.registerObserver(observer);
    }

    public void unregisterStateObserver(SDCardStateObserver observer) {
    	mStateObservable.unregisterObserver(observer);
    }
    
    public void notifyStateChanged(boolean mounted) {
    	mStateObservable.notifyStateChanged(mounted);
    }
	
	private static class SDCardStateObservable extends Observable<SDCardStateObserver> {
		
	    public void notifyStateChanged(boolean mounted) {
	        synchronized(mObservers) {
	            for (int i = mObservers.size() - 1; i >= 0; i--) {
	                mObservers.get(i).onChanged(mounted);
	            }
	        }
	    }
	}
}